# Model import
from rango.models import Category, Page
#Forms import
from rango.forms import CategoryForm, PageForm, UserForm, UserProfileForm
#authenticate
from django.contrib.auth import authenticate, login, logout
#decorators
from django.contrib.auth.decorators import login_required
#
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect

def encode_url(url):
    #For now function is to escape spaces only
    #ToDo escape all characters that do not obviously showing in the HTML
    if ' ' in url:
        return url.replace(' ', '_')
    else:
        return url
    
def decode_url(url):
    #For now function is to escape spaces only
    #ToDo escape all characters that do not obviously showing in the HTML
    if '_' in url:
        return url.replace('_', ' ')
    else:
        return url

def index(request):
    #Obtain the context from the HTTP request.
    context = RequestContext(request)
    
    #Get 5 ordered categories from Category model
    category_list = Category.objects.order_by('-likes')[:5]
    for category in category_list:
        category.url = encode_url(category.name)
    #Get 5 most visited pages
    page_list = Page.objects.order_by('-views')[:5]    
    
    context_dict = {'categories' : category_list,
                    'pages': page_list}

    #Render the response and send it back.
    return render_to_response('rango/index.html', context_dict, context)

def category(request, category_name_url):
    #Obtain the context from the HTTP request.
    context = RequestContext(request)
    
    category_name = decode_url(category_name_url)
    context_dict = {'category_name' : category_name}
    
    try:
        # Try if category name exists in DataBase
        category = Category.objects.get(name=category_name)        
        pages = Page.objects.filter(category=category)
        
        context_dict['category'] = category
        context_dict['pages'] = pages
    except Category.DoesNotExist:
        #Template displays "no category" message
        pass
        
    # Render
    return render_to_response('rango/category.html', context_dict, context)
        
def about(request):
    context = RequestContext(request)
    
    return render_to_response('rango/about.html')
# ----- Add Views
def add_category(request):
    # Obtain the context from the HTTP request.
    context = RequestContext(request)
    # A HTTP POST?
    if request.method == 'POST':
        # Save data
        form = CategoryForm(request.POST)
        # Is form data valid?
        if form.is_valid():
            # Save data to the database model
            form.save(commit=True)
            # Redirect to index page
            return redirect('index')
        else:
            print form.errors
    else:
        # Show form
        form = CategoryForm()
        
    context_dict = {'form':form}
    return render_to_response('rango/add_category.html',context_dict, context)
    
def add_page(request, category_name_url):
    context = RequestContext(request)
    
    category_name = decode_url(category_name_url)
    
    # HTTP with POST?
    if request.method == 'POST':
        form = PageForm(request.POST) # Different using of ModelForm constractor???
        
        if form.is_valid():
            # Get form without commit
            page = form.save(commit=False)
            
            #Retrieve the associated Category object so we cad add it
            cat = Category.objects.get(name=category_name)
            page.category = cat
            
            # Create default value for the number of views
            page.views = 0
            
            # Save new model instance
            page.save()
            # Redirect to current category page
            return redirect('category', category_name_url)
        else:
            #show form
            print form.errors
    else:
        form = PageForm()
        
    context_dict = {'category_name_url':category_name_url,
                   'category_name':category_name,
                   'form':form,
                   }
    return render_to_response('rango/add_page.html', context_dict, context)

# ----- User auth views
def register(request):
    #Registration form view
    #Obtain the context from the HTTP request.
    context = RequestContext(request)
    
    # Boolean variable to check if registration was successfull
    registered = False
    
    # HTTP with POST?
    if request.method == 'POST':
        # Get information from UserForm and UserProfileForm
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)
        
        if user_form.is_valid() and profile_form.is_valid():
            # Save the UserForm data to the DataBase (Can I save it after password hashing?)
            user = user_form.save()
            # Hash existing password
            user.set_password(user.password)
            user.save()
            
            # Save the Profile data to the DataBase, but before set User attribute
            profile = profile_form.save(commit=False)
            profile.user = user
            
            # Did the user provide a profile picture?
            # if so, we need to get if prom the input formand put it in the UserProfile model
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
                
            # Save UserProfile model instance.
            profile.save()
            
            registered = True
            
        # In case of some errors with forms print then
        else:
            print user_form.errors, profile_form.errors
    # If there was not POST in HTTP, Render UserForm and UserProfileForm
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    
    context_dict = { 'user_form': user_form,
                     'profile_form':profile_form,
                     'registered':registered,
                     }
    # Render the template
    return render_to_response('rango/register.html', context_dict, context)

def user_login(request):
    context = RequestContext(request)
    context_dict = {'errors' : []}
    
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        
        # Use django to check username/password,
        # User object is returned if it is
        user = authenticate(username=username, password=password)
        
        if user is not None:
            if user.is_active:
                # If account is valid and active, log in the user
                # and redirect to homepage
                login(request,user)
                return redirect('index')
            else:
                # An inactive account was used
                context_dict['errors'].append('You rango account is disabled.')
        else:
            # Bad ligin information provided
            context_dict['errors'].append('Invalid login details')
    
    # Provide blank login template
    return render_to_response('rango/login.html',context_dict, context)

#@login_required
def user_logout(request):
    # Since we know the user is logged in, we can now just log them out.
    logout(request)

    # Take the user back to the homepage.
    return redirect('index')

 # ----- Restricted views       
@login_required
def restricted(request):
    return HttpResponse('You are loged in!')
        
        
            
    

